// 侧边栏选择
// 获取侧边栏a标签
let user_a = document.querySelectorAll('.left a');
// console.log(user_a);
// 为每个a标签添加点击事件
for (let a of user_a) {
    a.onclick = function () {
        // 查找到选中的a标签
        let a_a = document.querySelector('a.active');
        // console.log(a_a);
        //查找到选中的a标签所对应的div
        let div = document.querySelector('.right>div.index');
        // console.log(div);

        //当有a标签为选中状态时
        if (a_a != null) {
            //对这个标签进行清除类名清除样式
            a_a.className = '';
        }
        //当有div为选中状态时
        if (this.dataset.id != div.id) {
            //对这个div进行清除类名清除样式
            div.className = '';
        }

        //再将点击的当前a标签添加类名active，为选中状态
        this.className = 'active';
        //根据a标签的data-id查找到对应id的div，添加选中状态
        document.querySelector(`#${this.dataset.id}`).className = 'index';
    }
}

//上传图片，预览图片
//选中到需要改变的元素
var preview = document.querySelector('#preview');
var eleFile = document.querySelector('#avatar');
eleFile.addEventListener('change', function () {
    // console.log(this.files);
    var file = this.files[0];
    // 确认选择的文件是图片                
    if (file.type.indexOf("image") == 0) {
        var reader = new FileReader();
        // console.log(reader);
        reader.readAsDataURL(file);
        reader.onload = function (e) {
            // 图片base64化
            var newUrl = this.result;
            // console.log(this.result);
            preview.style.backgroundImage = 'url(' + newUrl + ')';
        };
    }
});

// 订单头部选择
let lis = document.querySelectorAll('#my-order>.top>li');
for (let li of lis) {
    li.onclick = function () {
        let li_on = document.querySelector('#my-order>.top>li.on');
        if (li_on != null) {
            li_on.className = '';
        }
        this.className = 'on';
    }
}


//获取用户数据
//当页面加载完后立即执行函数
window.onload = function () {
    //获取保存的uid
    let uid = localStorage.getItem('uid');
    //进行ajax数据发访问
    ajax({
        //需要访问的服务端路由
        url: '/user/getUserById',
        //传输的类型
        type: 'get',
        //需要传输的数据
        data: uid,
        //成功时返回获取到返回的值
        success: function (data) {
            //对JSON字符串进行解析
            data = JSON.parse(data)[0];
            // console.log(data);

            //将获取的数据传给页面
            userId.value = data.uid;
            // console.log(userId.value);
            preview.style.backgroundImage = data.avatar;
            avatar.dataset.url = data.avatar;
            uname.value = data.uname;
            if (data.gender == 1) {
                man.checked = true;
            } else if (data.gender == 0) {
                woman.checked = true;
            } else {
                none.checked = true;
            }
            birthday.value = data.birthday;
            phone.value = data.phone;
            email.value = data.email;

            //获取个人数据的同时将id传给地址和订单函数
            //进行获取地址数据
            get_address(data.uid);
            //进行获取订单数据
            get_order(data.uid);
        },
        error: function (e) {
            console.log(e);
        }
    });
}

//用户名检验
function uname_check() {
    let _name = uname.value;

    if (!_name) {
        uname_msg.innerHTML = '用户名不能为空';
        //正则判断：A-Za-z0-9_中文字
    } else if (!(/^[A-Za-z0-9_\u4e00-\u9fa5]{3,12}$/.test(_name))) {
        uname_msg.innerHTML = '用户名为3~12位除特殊符号外的字符';
    } else {
        uname_msg.innerHTML = '';
    }
}

//邮箱检验
function email_check() {
    let _email = email.value;

    if (!_email) {
        email_msg.innerHTML = '邮箱不能为空';
    } else if (!(/^[A-Za-z0-9_-]+@[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)+$/.test(_email))) {
        email_msg.innerHTML = '邮箱格式不正确';
    } else {
        email_msg.innerHTML = '';
    }
}

//修改用户资料
function edit() {
    //点修改时再进行次数据判断
    uname_check();
    email_check();

    //当错误提示为空时执行
    if (uname_msg.innerHTML == '' && email_msg.innerHTML == '') {
        //获取数据
        let _uid = userId.value;
        // console.log(_uid);
        let _uname = uname.value;
        let _gender = '';
        if (woman.checked) {
            _gender = 0;
        } else if (man.checked) {
            _gender = 1;
        } else {
            _gender = 2;
        }
        let _email = email.value;
        let img = avatar.value.split("\\")[2];
        let _avatar = img ? `url(./images/user/${img})` : avatar.dataset.url;
        let _birthday = birthday.value;

        //弹窗确认
        if (confirm('是否确认修改？')) {

            ajax({
                url: '/user/update',
                type: 'post',
                //post数据传输时的格式
                data: `uid=${_uid}&uname=${_uname}&gender=${_gender}&email=${_email}&avatar=${_avatar}&birthday=${_birthday}`,
                success: function (data) {
                    if (data == 1) {
                        //当修改成功时将登录时保存的uname进行覆盖更新
                        localStorage.setItem('uname',_uname);
                        alert('更新成功！');
                        //通常一处地方的更改，都没有立即改变的，需要刷新一下
                        location.reload();
                    } else {
                        alert('更新失败！');
                    }
                },
                error: function (e) {
                    console.log(e);
                }
            });
        }
    }
}

// 显示隐藏密码
let unKnow = document.querySelectorAll('a.unknow');
for (let a_un of unKnow) {
    a_un.onclick = function () {
        //获取当前点击标签的上一个兄弟元素
        let input = this.previousElementSibling;
        //修改input的类型就可以实现点击显示密码，点击隐藏密码了
        if (input.type == 'password') {
            input.type = 'text';
        } else {
            input.type = 'password';
        }
    }
}

//检测旧密码是否正确
function check_old() {
    //先获取电话和旧密码的值
    let _phone = phone.value;
    let _old_pwd = old_pwd.value;
    if (_old_pwd) {
        //就密码不为空时
        ajax({
            url: '/user/login',
            type: 'get',
            //将电话和密码传入，进行查找数据
            data: `${_phone}&${_old_pwd}`,
            success: function (data) {
                //如果成功访问服务器回来的数据不为空
                //则表示找到了数据，证明旧密码正确
                if (data != 0) {
                    opMsg.innerHTML = '';
                } else {
                    opMsg.innerHTML = "密码错误，请重新输入";
                }
            },
            error: function (e) {
                console.log(e);
            }
        });
    } else {
        opMsg.innerHTML = "旧密码为空";
    }
}

//判断新密码
function check_new() {
    let _new_pwd = new_pwd.value;

    if (!_new_pwd) {
        npMsg.innerHTML = '新密码不能为空！';
    } else if (!(/^[A-Za-z0-9]{6,10}$/.test(_new_pwd))) {
        npMsg.innerHTML = '密码为字母或数字，6到10位';
    } else {
        npMsg.innerHTML = '';
    }
}

//修改用户密码
function change() {
    //修改前再判定一下是否有误
    check_old();
    check_new();

    if (opMsg.innerHTML == '' && npMsg.innerHTML == '') {
        let _uid = userId.value;
        // console.log(_uid);
        let _pwd = new_pwd.value;

        if (confirm('是否确认修改？')) {

            ajax({
                url: '/user/update',
                type: 'post',
                data: `uid=${_uid}&upwd=${_pwd}`,
                success: function (data) {
                    if (data == 1) {
                        alert('更新成功！');
                        location.reload();
                    } else {
                        alert('更新失败！');
                    }
                },
                error: function (e) {
                    console.log(e);
                }
            });
        }
    }
}

//添加地址的弹出层
//获取整体的遮罩层
let model = document.querySelector('.container-model');
//获取点击开启的按钮
let open = document.getElementById('open');
//获取弹出框的关闭按钮
let close_model = document.getElementById('close_model');


// 点击添加地址
open.addEventListener('click', function () {
    model.classList.add('show');
});
close_model.addEventListener('click', function () {
    model.classList.remove('show');
});
window.addEventListener("click", function (e) {
    e.target == model ? model.classList.remove("show") : false;
});

//数据判断
function check_city() {
    let _province = province.value;
    let _city = city.value;

    if (_province == '请选择省份' || _city == '请选择城市') {
        check_msg.innerHTML = '请选择地区';
    } else {
        check_msg.innerHTML = '';
    }
}

function check_name() {
    let _aname = aname.value;

    if (!_aname) {
        aname_msg.innerHTML = '请输入收件人';
    } else {
        aname_msg.innerHTML = '';
    }
}

function check_phone() {
    let _aphone = aphone.value;

    if (!_aphone) {
        aphone_msg.innerHTML = '请输入手机号';
    } else if (!(/^1[3-9]\d{9}$/.test(_aphone))) {
        aphone_msg.innerHTML = '手机号不正确';
    } else {
        aphone_msg.innerHTML = '';
    }
}

function check_address() {
    let _user_address = user_address.value;

    if (!_user_address) {
        address_msg.innerHTML = '请输入详情地址';
    } else {
        address_msg.innerHTML = '';
    }
}
function save_address() {
    //进行保存时再判断一下
    check_name();
    check_phone();
    check_city();
    check_address();

    if (aname_msg.innerHTML == '' && aphone_msg.innerHTML == '' && check_msg.innerHTML == '' && address_msg.innerHTML == '') {
        let _uid = userId.value;
        let _aname = aname.value;
        let _aphone = aphone.value;
        let _province = province.value;
        let _city = city.value;
        let _user_address = user_address.value;

        let str = `uid=${_uid}&addressName=${_aname}&province=${_province}&city=${_city}&address=${_user_address}&cellphone=${_aphone}`;

        ajax({
            url: '/user/address',
            type: 'post',
            data: str,
            success: function(data){
                alert('添加成功！');
                location.reload();
            },
            error: function(e){
                console.log(e);
            }
        });
    }
}

// 获取收货地址
function get_address(id){
    let list_item = document.querySelector('#address .list-item');

    ajax({
        url: '/user/get_address',
        type: 'get',
        data: id,
        success: function(data){
            data = JSON.parse(data);
            let address_data = {
                data: '',
            };
            //不为空是将获取到的数据保存到一个对象中
            if(data!=null){
                address_data.data = data;
                list_item.innerHTML = template('address_list',address_data);
            }else{
                list_item.innerHTML = template('address_list',address_data);
            }
        },
        error: function(e){
            console.log(e);
        }
    });
}

//删除地址
function delete_address(id){
    if(confirm('确认删除此地址吗？')){
        ajax({
            url: '/user/del_address',
            type: 'get',
            data: id,
            success: function(data){
                alert("删除成功！");
            },
            error: function(e){
                console.log(e);
            }
        });
    }
}

// 获取订单
function get_order(id){
    let order = document.querySelector('#my-order .bottom');

    ajax({
        url: '/user/get_order',
        type: 'get',
        data: id,
        success: function(data){
            data = JSON.parse(data);
            // console.log(data);
            let order_data = {
                order : '',
            }
            if(data!=null){
                for (let i=0;i<data.length;i++) {
                    data[i].total = data[i].pnum * data[i].price;
                }
                order_data.order = data;
            }
            order.innerHTML = template('order_list',order_data);
        },
        error: function(e){
            console.log(e);
        }
    });
}

//取消订单
function del_order(id){
    // console.log(id);
    if(confirm('是否取消订单')){
        ajax({
            url: '/user/del_order',
            type: 'get',
            data: id,
            success: function(data) {
                alert("取消订单成功");
                location.reload();
            },
            error: function(e){
                console.log(e);
            }
        });
    }
}

//支付订单
function order_updateByOid(id){
    if(confirm('确认支付')){
        ajax({
            url: '/user/order_updateByOid',
            type: 'post',
            data: `status=2&oid=${id}`,
            success: function(data) {
                alert('支付成功，等待发货！');
                location.reload();
            },
            error: function(e){
                console.log(e);
            }
        });
    }
}
